import React, { useEffect, useRef, useState } from 'react'
import {
  Button,
  message,
  Modal,
  Empty,
  Dropdown,
  notification,
  Spin,
  Tag,
  Checkbox,
  Form,
  Table,
  Radio,
  Select,
  DatePicker,
} from 'antd'
import * as mathjs from 'mathjs'
import useGetTableData from '@/hooks/useGetTableData'
import { exportReorderInfo, getReorderAdviceList, exportAdviceIntentOrder, getOTBInfo } from '@/api/reorder'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm, useWatch } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { IMPORT_FILE_ENUM } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import './index.less'
import { UploadOutlined, FullscreenOutlined, FullscreenExitOutlined, ImportOutlined } from '@ant-design/icons'
import { CPZ_OPTIONS, PURCHASEWAY_OPTIONS, PURCHASEWAY_OPTIONS_NAME } from '@/constant/purchase'
import { getProductClassConfigByType, getSpuOptions, importExpandSkuDetail } from '@/api/goods'
import dayjs, { Dayjs } from 'dayjs'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import {
  findDataTypeAndCollectIds,
  exportNotification,
  handleDetailFactory,
  importNotificationSpec,
  importNotification,
} from '@/utils/util'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import { changeFullScreen } from '@/store/reducers/user'
import Descriptions from '@/components/Descriptions'
import { useFormExport } from './useForm'
import { EditFormVertical } from '@/components/CustomForm'
import ImportFileModal from '@/components/ImportFileModal'
import useCachePage from '@/hooks/useCachePage'
import useGetClassNames from '@/hooks/useGetClassNames'
dayjs.extend(weekOfYear)
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const [form] = useForm()
  const [FormExport] = useForm()
  const [FormUpload] = useForm()
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const [expandedType, setexpandedType] = useState<'style' | 'color' | 'cup' | 'size'>('style')
  const [isSpuInfoShow, setisSpuInfoShow] = useState(false)
  const [isHisInfoShow, setisHisInfoShow] = useState(false)
  const [isViewProcessShow, setisViewProcessShow] = useState(false)
  const [hasKnowCenter, sethasKnowCenter] = useState(true)
  const [hasKnowInModal, sethasKnowInModal] = useState(true)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const isFullScreen = useAppSelector((state) => state.user.is_full_screen)
  const [isExportModal, setisExportModal] = useState(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const { setCachePage, getCachePage } = useCachePage()
  const dispatch = useAppDispatch()
  const { classIdOptions } = useGetClassNames()
  const navigate = useNavigate()
  const [exportLoading, setexportLoading] = useState(false)
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [classBig, setclassBig] = useState<(IOptionItem & { id: string })[]>([])
  const [SeriesOptions] = useState<IOptionItem[]>([])
  const [PriceOptions] = useState<IOptionItem[]>([])
  const [spinning, setspinning] = useState<boolean>(false)
  const [taginfoList, settaginfoList] = useState<IDesListType>([])
  const [hisinfoList, sethisinfoList] = useState<IDesListType>([
    { label: '款式编码', key: 'similarSpuCode', content: '-' },
    { label: '款式名称', key: 'similarSpuName', content: '-' },
    { label: '年份', key: 'similarSpuProductYear', content: '-' },
    { label: '吊牌价', key: 'similarSpuListPrice', content: '-' },
  ])
  const [groupList, setgroupList] = useState<IDesListType>([
    { label: '分组规则', key: 'weekRateGroupKey', content: '-' },
  ])
  const [processList, setprocessList] = useState<IDesListType>([
    { label: '基础陈列量', key: 'displayNum', content: '-' },
    { label: '最晚到货时间', key: 'lastDate', content: '-' },
    { label: '返单点库存', key: 'reorderInventory', content: '-' },
    { label: '剩余返单次数', key: 'leftReorderNum', content: '-' },
    { label: '返单周期', key: 'reorderPeriod', content: '-' },
    { label: '总缺口量', key: 'leftNum', content: '-' },
  ])
  const displayYear = () => {
    const currentDate = dayjs()
    const currentMonth = currentDate.month() + 1
    if (currentMonth >= 1 && currentMonth <= 11) {
      return currentDate
    } else if (currentMonth === 12) {
      return currentDate.add(1, 'year')
    }
  }
  const displaySeason = () => {
    const currentDate = dayjs()
    const currentMonth = currentDate.month() + 1
    if ((currentMonth >= 1 && currentMonth <= 5) || currentMonth === 12) {
      return '春夏'
    } else {
      return '秋冬'
    }
  }
  const [otbYear, setotbYear] = useState(() => displayYear())
  const [otbSeason, setotbSeason] = useState(() => displaySeason())
  const [otbInfo, setotbInfo] = useState<Record<string, any>>({})
  const { tableProps, params, setParams, search } = useGetTableData<ITableData>(getReorderAdviceList, {
    form: form,
    defaultFieldsParams: {
      lastMondaydate: dayjs().subtract(1, 'week').startOf('week'),
    },
    immediatelySend: false,
    pageSize: 1,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  // 1 相似款数据  2 分类数据 默认为分类数据
  const [dataType, setdataType] = useState<1 | 2>(2)
  useEffect(() => {
    getProductClassConfig()
    return () => {
      dispatch(changeFullScreen(false))
    }
  }, [])
  useEffect(() => {
    if (!isFullScreen && window.innerWidth < 1500) {
      notification.open({
        type: 'warning',
        message:
          '当前页面数据较多，为了提升您的浏览体验，建议调整页面缩放比例(快捷键：ctrl+减号)或切换为全屏模式，以更好地查看列表信息。',
      })
    }
  }, [])
  useEffect(() => {
    if (classBig && classBig.length > 0) {
      handleCacheData()
    }
  }, [classBig])
  useEffect(() => {
    if (expandedType === 'style') {
      setexpandedRowKeys([])
    } else if (expandedType === 'color') {
      const data = tableProps?.dataSource?.map((item) => item.id)
      setexpandedRowKeys(data)
    } else if (expandedType === 'cup') {
      //打开所有的色
      const ids = findDataTypeAndCollectIds(tableProps.dataSource, (node) => node.productDataType === 'SKC')
      setexpandedRowKeys(ids)
    } else if (expandedType === 'size') {
      if (form.getFieldValue('largeClassName') === '文胸') {
        const ids = findDataTypeAndCollectIds(tableProps.dataSource, (node) => {
          if (node?.cupType == 0) {
            return node.productDataType === 'SKC'
          } else {
            return node.productDataType === 'SKC_CUP'
          }
        })
        setexpandedRowKeys(ids)
      } else {
        const ids = findDataTypeAndCollectIds(tableProps.dataSource, (node) => node.productDataType === 'SKC')
        setexpandedRowKeys(ids)
      }
    }
  }, [tableProps.dataSource])
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string
    }>({ type, auth: 1 })
    const classBig =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.className,
          id: item.classConfigId,
        }
      }) || []
    setclassBig(classBig)
    const cacheData = getCachePage()
    if (classBig.length > 0 && cacheData == null) {
      form.setFieldValue('largeClassName', classBig[0].value)
      const vals = await form.validateFields()
      onSearch(vals)
    }
  }
  const onViewSpuInfo = (info: ITableData) => {
    setisSpuInfoShow(true)
    const taginfoList: IDesListType = [
      { label: '商品系列', key: 'productSeries', content: '-', showKey: 'productSeries' },
      { label: '版型', key: 'patternType', content: '-', showKey: 'patternType' },
      { label: '领型', key: 'collarType', content: '-', showKey: 'collarType' },
      { label: '花型', key: 'flowerType', content: '-', showKey: 'flowerType' },
      { label: '杯型', key: 'moduleType', content: '-', showKey: 'moduleType' },
      { label: '后比', key: 'laterThan', content: '-', showKey: 'laterThan' },
      { label: '模杯材质', key: 'moldCupMaterial', content: '-', showKey: 'moldCupMaterial' },
      { label: '模杯厚度', key: 'moldCupThickness', content: '-', showKey: 'moldCupThickness' },
      { label: '模杯形状', key: 'moldCupShape', content: '-', showKey: 'moldCupShape' },
      { label: '排扣', key: 'breasted', content: '-', showKey: 'breasted' },
      { label: '厚度', key: 'thicknessCode', content: '-', showKey: 'thicknessCode' },
      { label: '功能', key: 'functionType', content: '-', showKey: 'functionType' },
      { label: '风格', key: 'styleCode', content: '-', showKey: 'styleCode' },
      { label: '图案布局', key: 'patternLayoutCode', content: '-', showKey: 'patternLayoutCode' },
      { label: '元素', key: 'elementCode', content: '-', showKey: 'elementCode' },
      { label: '工艺', key: 'technicsCode', content: '-', showKey: 'technicsCode' },
      { label: '面料', key: 'fabricType', content: '-', showKey: 'fabricType' },
      { label: '适卖温度', key: 'sellTempCode', content: '-', showKey: 'sellTempCode' },
      { label: '克重', key: 'gramWeight', content: '-', showKey: 'gramWeight' },
      { label: '价格带', key: 'priceTagCode', content: '-', showKey: 'priceTagCode' },
      { label: '年龄段', key: 'ageCode', content: '-', showKey: 'ageCode' },
    ]
    if (info?.productTemplateVO && info?.productTemplateVO?.notShow?.length > 0) {
      const filtertaginfoList = taginfoList.filter((item) => !info?.productTemplateVO?.notShow?.includes(item.showKey!))
      handleDetailFactory(filtertaginfoList, info?.productSpuInfo, settaginfoList)
      return
    }
    handleDetailFactory(taginfoList, info?.productSpuInfo, settaginfoList)
  }
  const onViewHisInfo = (info: ITableData) => {
    setisHisInfoShow(true)
    dataType == 2
      ? handleDetailFactory(groupList, info, setgroupList)
      : handleDetailFactory(hisinfoList, info, sethisinfoList)
  }
  const onViewProcessInfo = (info: ITableData) => {
    setisViewProcessShow(true)
    handleDetailFactory(processList, info, setprocessList)
  }
  const checkboxChange = async (currentResetFlag: boolean) => {
    const data = await form.validateFields()
    onSearch({ ...data, current: currentResetFlag ? params.current : 1, size: params.size })
  }
  const onCancelModal = () => {
    setisSpuInfoShow(false)
    setisHisInfoShow(false)
    setisViewProcessShow(false)
    setisExportModal(false)
  }
  const handleExport = async () => {
    setexportLoading(true)
    setspinning(true)
    const data = await FormExport.validateFields()
    const res = await exportReorderInfo({ ...params, ...data, dataType })
      .catch(() => setspinning(false))
      .finally(() => {
        setexportLoading(false)
        onCancelModal()
      })
    if (res?.code === 200 && res?.data) {
      await exportNotification(res?.data, navigate).finally(() => setspinning(false))
    }
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const lastMondaydate = form.getFieldValue('lastMondaydate')
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    setspinning(true)
    const res = await importExpandSkuDetail<{ linkUrl: string }>(file, {
      weekNum: dayjs(lastMondaydate).week(),
      startDate: dayjs(lastMondaydate).startOf('week').format('YYYY-MM-DD'),
      endDate: dayjs(lastMondaydate).endOf('week').format('YYYY-MM-DD'),
    })
      .catch(() => setspinning(false))
      .finally(() => {
        setexportLoading(false)
        onUploadFileCancel()
      })
    if (res?.code === 200 && res?.data) {
      if (typeof res?.data === 'string') {
        await importNotificationSpec(res?.data, navigate, '/task/center/list?type=REORDER').finally(() =>
          setspinning(false),
        )
        onSearch({ ...form.getFieldsValue(), current: params.current, size: params.size })
      } else {
        setspinning(false)
        importNotification(res?.data?.linkUrl)
      }
    }
    if (res?.code === 820000) {
      setspinning(false)
      notification.open({
        type: 'warning',
        message: res?.msg,
      })
    }
  }
  const onParamsChange = async ({ year, seasonName }: { year?: Dayjs; seasonName?: string }) => {
    const formatyear = year ? dayjs(year).year() : dayjs(otbYear).year()
    const formatseasonName = seasonName ? seasonName : otbSeason
    const largeClassId = classBig?.find((item) => item.label == form.getFieldValue('largeClassName'))?.id
    const res = await getOTBInfo({
      year: formatyear + '',
      seasonName: formatseasonName,
      largeClassName: form.getFieldValue('largeClassName'),
      largeClassId,
    })
    setotbInfo(res?.data || {})
  }
  const ExtraCom = () => {
    return (
      <div className="flex_column">
        <div className="table_extra_flex_wrapbox">
          <div className="table_extra_flex">
            <Form form={form} className="suggestion_form" initialValues={{ selectParams: 'style' }}>
              <Form.Item noStyle name="selectKey">
                <Checkbox.Group
                  onChange={() => checkboxChange(false)}
                  options={[
                    {
                      label: '只看建议返单的款',
                      value: 'reorderFlag',
                    },
                    {
                      label: '只看有修正返单量的款',
                      value: 'amendReordrNum',
                    },
                    {
                      label: '只看扩渗透的款',
                      value: 'expand',
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item noStyle name="selectParams">
                <Radio.Group
                  buttonStyle="outline"
                  onChange={() => checkboxChange(true)}
                  options={
                    form.getFieldValue('largeClassName') == '文胸'
                      ? [
                          {
                            label: '展开到款',
                            value: 'style',
                          },
                          {
                            label: '展开到色',
                            value: 'color',
                          },
                          {
                            label: '展开到杯型',
                            value: 'cup',
                          },
                          {
                            label: '展开到尺码',
                            value: 'size',
                          },
                        ]
                      : [
                          {
                            label: '展开到款',
                            value: 'style',
                          },
                          {
                            label: '展开到色',
                            value: 'color',
                          },
                          {
                            label: '展开到尺码',
                            value: 'size',
                          },
                        ]
                  }
                />
              </Form.Item>
            </Form>
          </div>
        </div>
        {!isFullScreen && hasKnowCenter && (
          <div className="center_notice">
            <div className="info_box">
              <div className="info_box_row">
                <div>
                  <span>当前计算周：</span>
                  {dayjs(form.getFieldValue('lastMondaydate')).startOf('week').format('YYYY-MM-DD')} ~
                  {dayjs(form.getFieldValue('lastMondaydate')).endOf('week').format('YYYY-MM-DD')}
                </div>
                <div>
                  <span>计算完成时间：</span>
                  {dayjs(form.getFieldValue('lastMondaydate')).startOf('week').format('YYYY-MM-DD')}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 12 }}>
                <div style={{ marginTop: 2, display: 'flex', alignItems: 'center' }}>
                  <span>年份：</span>
                  <DatePicker
                    allowClear={false}
                    value={otbYear}
                    onChange={(val) => {
                      onParamsChange({ year: val })
                      setotbYear(val)
                    }}
                    style={{ width: 50, padding: '0 6px' }}
                    suffixIcon={null}
                    placeholder=""
                    picker="year"
                  ></DatePicker>
                </div>
                <div style={{ marginTop: 2, display: 'flex', alignItems: 'center' }}>
                  <span>订单季节：</span>
                  <Select
                    style={{ width: 70, textAlign: 'center' }}
                    value={otbSeason}
                    onChange={(val) => {
                      onParamsChange({ seasonName: val })
                      setotbSeason(val)
                    }}
                    placeholder=""
                    allowClear={false}
                    suffixIcon={null}
                    options={DICTDATA.order_season}
                  ></Select>
                </div>
              </div>
              <div style={{ display: 'flex' }}>
                <div style={{ marginTop: 2 }}>OTB吊牌采购情况：</div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div>
                    当前：
                    <span style={{ color: otbInfo.currentRatio > 1 ? '#FF0000' : '#3F5EFF' }}>
                      {otbInfo.currentRatio > 1 ? '【超额】' : '【未超额】'}
                    </span>
                    <span>
                      {otbInfo.currentRatio ? mathjs.multiply(mathjs.bignumber(otbInfo.currentRatio), 100) + '%' : '-'}
                      （{otbInfo?.currentUsedTagPrice ? otbInfo?.currentUsedTagPrice : '-'} / {otbInfo?.finalTagPrice}）
                    </span>
                  </div>
                  <div>
                    按意向返单需求量下单后:
                    <span style={{ color: otbInfo.currentRatio > 1 ? '#FF0000' : '#3F5EFF' }}>
                      {otbInfo.currentRatio > 1 ? '【超额】' : '【未超额】'}
                    </span>
                    <span>
                      {otbInfo.afterOrderRatio
                        ? mathjs.multiply(mathjs.bignumber(otbInfo.afterOrderRatio), 100) + '%'
                        : '-'}
                      （{otbInfo.afterOrderTagPrice ? otbInfo.afterOrderTagPrice : '-'} / {otbInfo?.finalTagPrice}）
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="has_know" onClick={() => sethasKnowCenter(false)}>
              我知道了
            </div>
          </div>
        )}
        <div className="table_extra_flex_wrapbox">
          <div className="table_extra_flex">
            <PermissionButton
              permission="penetratePlan"
              icon={<ImportOutlined />}
              loading={exportLoading}
              onClick={() => {
                const lastMondaydate = form.getFieldValue('lastMondaydate')
                if (!lastMondaydate) {
                  message.warning('请选择计算周')
                  return
                }
                setisUploadFileShow(true)
              }}
            >
              导入修正返单量/扩渗透计划量
            </PermissionButton>
          </div>
          <div className="table_extra_flex">
            <Button
              icon={isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
              onClick={async () => {
                await dispatch(changeFullScreen(!isFullScreen))
              }}
            ></Button>
            <PermissionButton
              permission="suggestionExport"
              icon={<UploadOutlined />}
              loading={exportLoading}
              onClick={() => {
                setisExportModal(true)
              }}
            >
              导出
            </PermissionButton>
            <PermissionButton
              permission="sugIntentOrderExport"
              icon={<UploadOutlined />}
              loading={exportLoading}
              onClick={async () => {
                setexportLoading(true)
                setspinning(true)
                const res = await exportAdviceIntentOrder({ ...params, dataType })
                  .catch(() => setspinning(false))
                  .finally(() => {
                    setexportLoading(false)
                  })
                if (res?.code === 200 && res?.data) {
                  await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                }
              }}
            >
              导出意向订单
            </PermissionButton>
          </div>
        </div>
      </div>
    )
  }
  const onSearch = (vals: any) => {
    sethasKnowCenter(true)
    const paramsData = {
      ...vals,
      productYear: vals.productYear ? dayjs(vals.productYear).format('YYYY') : null,
      lastMondaydate: vals?.lastMondaydate
        ? dayjs(vals?.lastMondaydate).startOf('week').format('YYYY-MM-DD')
        : dayjs().subtract(1, 'week').startOf('week').format('YYYY-MM-DD'),
      largeClassName: vals?.largeClassName ? vals.largeClassName : classBig.length > 0 ? classBig[0].value : null,
      midClassName: vals?.fineClassNameList?.length > 1 ? vals?.fineClassNameList[1] : null,
      smallClassName: vals?.fineClassNameList?.length > 2 ? vals?.fineClassNameList[2] : null,
      fineClassName: vals?.fineClassNameList?.length > 3 ? vals?.fineClassNameList[3] : null,
      dataType,
    }
    const filterParams = {
      reorderFlag: null,
      amendReordrNum: false,
      expand: false,
    } as {
      reorderFlag: null | '是'
      amendReordrNum: boolean
      expand: boolean
    }
    if (vals.selectKey && vals.selectKey.length > 0) {
      if (vals.selectKey.includes('reorderFlag')) {
        filterParams.reorderFlag = '是'
      }
      if (vals.selectKey.includes('amendReordrNum')) {
        filterParams.amendReordrNum = true
      }
      if (vals.selectKey.includes('expand')) {
        filterParams.expand = true
      }
    }
    if (vals.selectParams) {
      setexpandedType(vals.selectParams)
    } else {
      setexpandedType('style')
    }
    const cacheData = getCachePage()
    setCachePage({
      ...paramsData,
      ...filterParams,
      SpuOptions: SpuOptions.length > 0 ? SpuOptions : cacheData?.SpuOptions?.length > 0 ? cacheData?.SpuOptions : [],
      expandedType,
    })
    const { selectKey, selectParams, fineClassNameList, ...newParamsData } = paramsData
    search({
      ...newParamsData,
      ...filterParams,
    })
    onParamsChange({})
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) return
    const selectKey = []
    if (cacheData.reorderFlag === '是') {
      selectKey.push('reorderFlag')
    }
    if (cacheData.amendReordrNum) {
      selectKey.push('amendReordrNum')
    }
    if (cacheData.expand) {
      selectKey.push('expand')
    }
    form.setFieldsValue({
      ...cacheData,
      lastMondaydate: cacheData.lastMondaydate ? dayjs(cacheData.lastMondaydate) : null,
      productYear: cacheData.productYear ? dayjs(cacheData.productYear) : null,
      selectKey,
    })
    setSpuOptions(cacheData?.SpuOptions || [])
    const { SpuOptions, expandedType, ...newCacheData } = cacheData
    onSearch({
      ...newCacheData,
      selectKey,
    })
  }
  const onReset = async () => {
    form.resetFields()
    form.setFieldsValue({
      lastMondaydate: dayjs().subtract(1, 'week').startOf('week'),
      largeClassName: classBig.length > 0 ? classBig[0].value : null,
    })
    onSearch({
      lastMondaydate: dayjs().subtract(1, 'week').startOf('week').format('YYYY-MM-DD'),
      largeClassName: classBig.length > 0 ? classBig[0].value : null,
      midClassName: null,
      smallClassName: null,
      fineClassName: null,
      spuCode: null,
      productSeries: null,
      listPriceSaleVal: null,
      productYear: null,
      seasonClassifyNames: null,
      purchaseType: null,
      salesTags: null,
      current: 1,
      size: 1,
    })
  }
  const ondataTypeChange = () => {
    setdataType(dataType == 2 ? 1 : 2)
  }
  // 只需要更新时执行
  useUpdateEffect(() => {
    onSearch({ ...form.getFieldsValue(), current: 1, size: params.size })
  }, [dataType])
  function useUpdateEffect(effect: () => void, dependencies: any[]) {
    const isFirstRender = useRef(true)
    useEffect(() => {
      if (isFirstRender.current) {
        isFirstRender.current = false
      } else {
        effect()
      }
    }, dependencies)
  }
  return (
    <PageContainer className="reorder_suggestion_page">
      {
        <SearchForm
          className={`${isFullScreen ? 'fly_to_sky' : ''}`}
          isFold
          params={params}
          form={form}
          searchConfig={[
            {
              label: '计算周',
              name: 'lastMondaydate',
              type: 'DatePicker',
              config: {
                showWeek: false,
                picker: 'week',
                maxDate: dayjs().subtract(1, 'week'),
                format: (val: any) =>
                  `${dayjs(val).startOf('week').format('YYYY-MM-DD')} ~ ${dayjs(val)
                    .endOf('week')
                    .format('YYYY-MM-DD')}`,
              },
              rules: [{ required: true, message: '请选择计算周' }],
            },
            {
              label: '大类',
              name: 'largeClassName',
              type: 'Select',
              option: classBig,
              rules: [{ required: true, message: '请选择大类' }],
              config: {
                onChange: (val: string) => {
                  if (val === '文胸') {
                    FormExport.setFieldValue('exportDataTypeList', ['SPU', 'SKC', 'SKC_CUP', 'SKU'])
                  }
                },
              },
            },
            {
              name: 'fineClassNameList',
              label: '款式分类',
              type: 'Cascader',
              option: classIdOptions,
              placeholder: '请选择款式分类',
              config: {
                changeOnSelect: true,
                fieldNames: { label: 'className', value: 'className', children: 'childrenList' },
              },
            },
            {
              label: 'SPU商品',
              name: 'spuCode',
              type: 'Select',
              option: SpuOptions,
              placeholder: '款式编码/款式名称/助记码',
              config: {
                suffixIcon: null,
                showSearch: true,
                filterOption: false,
                optionFilterProp: 'label',
                onSearch: handleSearchSpuOptions,
                notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              },
            },
            {
              label: '商品系列',
              name: 'productSeries',
              type: 'Select',
              option: SeriesOptions,
              placeholder: '请输入商品系列',
              config: {
                mode: 'tags',
                maxTagCount: 'responsive',
                notFoundContent: null,
              },
            },

            {
              label: '吊牌价',
              name: 'listPriceSaleVals',
              type: 'Select',
              option: PriceOptions,
              placeholder: '请输入吊牌价',
              config: {
                mode: 'tags',
                maxTagCount: 'responsive',
                notFoundContent: null,
              },
            },

            {
              label: '商品年份',
              name: 'productYear',
              type: 'DatePicker',
              config: {
                picker: 'year',
                format: 'YYYY',
              },
            },
            {
              name: 'seasonClassifyNames',
              label: '季节分组',
              type: 'Select',
              option: DICTDATA.season_classify,
              placeholder: '请选择季节分组',
              config: {
                suffixIcon: null,
                showSearch: true,
                optionFilterProp: 'label',
                filterOption: true,
                mode: 'multiple',
                maxTagCount: 'responsive',
              },
            },
            {
              label: '采购渠道',
              name: 'purchaseType',
              type: 'Select',
              option: PURCHASEWAY_OPTIONS_NAME,
              config: {
                suffixIcon: null,
                showSearch: true,
                optionFilterProp: 'label',
                filterOption: true,
              },
            },
            {
              label: '畅平滞标签',
              name: 'salesTags',
              type: 'Select',
              option: CPZ_OPTIONS,
              config: {
                suffixIcon: null,
                showSearch: true,
                optionFilterProp: 'label',
                filterOption: true,
                mode: 'multiple',
                maxTagCount: 'responsive',
              },
            },
          ]}
          onFinish={onSearch}
          onReset={onReset}
          extra={<ExtraCom />}
        ></SearchForm>
      }
      {isFullScreen && (
        <div className="fullscreen_extra">
          <ExtraCom />
        </div>
      )}
      <CustomTable
        className={`small_sise_customtable${isFullScreen ? ' nomargin' : ''}`}
        bordered
        columns={useIndexColumns({
          navigate,
          onViewSpuInfo,
          onViewHisInfo,
          onViewProcessInfo,
          dataType,
          ondataTypeChange,
          isShowCup: form.getFieldValue('largeClassName') === '文胸',
        })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        isScrollY={!isFullScreen}
        scrollY={
          isFullScreen
            ? window.innerHeight - (document.querySelector('.ant-table-thead')?.clientHeight || 0) - 160
            : undefined
        }
        tableRowGray={() => {
          return 'fkingjs'
        }}
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
        pageSizeOptions={[1, 5, 10]}
        extraHeight={20}
      />
      <Modal width={1000} title="商品标签信息" maskClosable open={isSpuInfoShow} onCancel={onCancelModal} footer={null}>
        <Descriptions column={{ xxl: 4, xl: 4, lg: 3, md: 2, sm: 1, xs: 1 }} title="标签信息" list={taginfoList}>
          {taginfoList?.length === 0 ? (
            <div style={{ width: '100%', height: 200 }}>
              <Empty
                style={{
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
              />
            </div>
          ) : null}
        </Descriptions>
      </Modal>
      <Modal
        width={1000}
        title={dataType == 2 ? '分组数据' : '历史相似款数据'}
        maskClosable
        open={isHisInfoShow}
        onCancel={onCancelModal}
        footer={null}
      >
        <Descriptions
          column={{ xxl: 4, xl: 4, lg: 3, md: 2, sm: 1, xs: 1 }}
          title=""
          list={dataType == 2 ? groupList : hisinfoList}
        ></Descriptions>
      </Modal>
      <Modal
        width={1000}
        title="返单推算过程"
        maskClosable
        open={isViewProcessShow}
        onCancel={onCancelModal}
        footer={null}
        wrapClassName="reorder_modal_process"
      >
        {hasKnowInModal && (
          <div className="header_notice">
            <div className="info_box">
              <div className="info_box_row">基础陈列量:SKC单店陈列量*本周库存门店数</div>
              <div className="info_box_row">返单点库存:返单周期销量+到货异常天数销量+基础陈列量</div>
              <div className="info_box_row">总缺口量:下市前预估总销量-总库存</div>
              <div className="info_box_row">剩余返单次数:(最晚到货时间-当前时间)/返单周期</div>
            </div>
            <div className="has_know" onClick={() => sethasKnowInModal(false)}>
              我知道了
            </div>
          </div>
        )}
        <Descriptions column={{ xxl: 4, xl: 4, lg: 3, md: 2, sm: 1, xs: 1 }} title="" list={processList}></Descriptions>
      </Modal>
      <Modal
        title="导出选项"
        maskClosable
        open={isExportModal}
        onCancel={onCancelModal}
        okText="导出"
        onOk={handleExport}
        confirmLoading={exportLoading}
      >
        <EditFormVertical
          editConfig={useFormExport({ isCup: form.getFieldValue('largeClassName') == '文胸' })}
          form={FormExport}
          initialValues={{
            exportDataTypeList: ['SPU', 'SKC', 'SKU'],
            withPicture: 0,
          }}
        />
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.EXPAND_PENETRATION_IMPORT}
      ></ImportFileModal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
